//引用axios请求接口
// 云函数入口文件
const cloud = require('wx-server-sdk')


cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

const axios = require('axios')

const URL = 'https://apis.imooc.com/personalized?icode=023BFC723EC68B57'

const playlistCollection = db.collection('playlist')

const MAX_LIMIT = 100

// 云函数入口函数
exports.main = async (event, context) => {
  const countResult = await playlistCollection.count()//获取当前总条数
  const total = countResult.total//获取当前对象总条数
  const batchTimes = Math.ceil(total / MAX_LIMIT)//计算获取歌单次数(云函数单词上限100条)
  const tasks = []//放置promise集合
  for (let i = 0; i < batchTimes; i++) {
    let promise = playlistCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()//从第0条开始取
    tasks.push(promise)
  }
  let list = {
    data: []
  }
  if (tasks.length > 0) {
    list = (await Promise.all(tasks)).reduce((acc, cur) => {//当所有任务执行完成后,迭代数据,赋值给list
      return {
        data: acc.data.concat(cur.data)
      }
    })
  }

  // axios发送请求，请求新的URL
  const {
    data
  } = await axios.get(URL)
  if (data.code >= 1000) {
    console.log(data.msg)
    return 0
  }
  const playlist = data.result

  const newData = []  //歌单去重
  for (let i = 0, len1 = playlist.length; i < len1; i++) {
    let flag = true
    for (let j = 0, len2 = list.data.length; j < len2; j++) {
      if (playlist[i].id === list.data[j].id) {
        flag = false
        break
      }
    }
    if (flag) {
      //给每个歌单信息增加createTime属性
      let pl = playlist[i]
      pl.createTime = db.serverDate()
      // newData.push(playlist[i])
      newData.push(pl)
    }
  }
  console.log(newData)  //去重的歌单数据添加到数据库
  // 更新代码: 一次性批量插入数据
  if (newData.length > 0) {
    await playlistCollection.add({
      data: [...newData]
    }).then((res) => {
      console.log('插入成功')
    }).catch((err) => {
      console.log(err)
      console.error('插入失败')
    })
  }

  return newData.length
}